const boleanWebsocket = {
  data () {
    return {
      // websocket 变量
      ws: null,
      // 心跳检测定时器
      timeoutObj: null,
      // 心跳检测服务器响应定时器
      serverTimeoutObj: null,
      // 重连 websocket 的定时器
      tt: null,
      // 是否连接上 websocket
      lockReconnect: false,
      // 是否需要心跳检测
      isNeedHeartCheck: false,
      // websocket 心跳检测间隔时间
      timeout: 3000
    }
  },
  methods: {
    // 创建 websocket
    createWebSocket (wsUrl) {
      var self = this
      try {
        self.ws = new WebSocket(wsUrl)
        self.initWebSocket(wsUrl)
      } catch (e) {
        console.error(e)
        self.reconnectWebsocket(wsUrl)
      }
    },
    // 初始化 websocket
    initWebSocket (wsUrl) {
      this.ws.onclose = () => {
        // console.log('websocket连接关闭');
        this.reconnect(wsUrl)
      }
      this.ws.onerror = () => {
        // console.log('websocket连接发生异常');
        this.reconnect(wsUrl)
      }
      this.ws.onopen = () => {
        // 心跳检测重置
        if (this.isNeedHeartCheck) {
          this.heartCheck()
        }
      }
      this.ws.onmessage = (event) => {
        // 拿到任何消息都说明当前连接是正常的
        this.handleWebsocketMessage(event.data)

        // 心跳检测重置
        if (this.isNeedHeartCheck) {
          this.heartCheck()
        }
      }
    },
    // websocket 心跳检测
    heartCheck () {
      this.timeoutObj && clearTimeout(this.timeoutObj)
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
      this.timeoutObj = setTimeout(() => {
        // 这里发送一个心跳，后端收到后，返回一个心跳消息，
        this.ws.send('心跳')
        this.serverTimeoutObj = setTimeout(() => {
          this.ws.close()
        }, this.timeout)
      }, this.timeout)
    },
    // 重连 websocket
    reconnectWebsocket (url) {
      if (this.lockReconnect) {
        return
      };
      this.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      this.tt && clearTimeout(this.tt)
      this.tt = setTimeout(() => {
        this.createWebSocket(url)
        this.lockReconnect = false
      }, 4000)
    }
  }
}

export default boleanWebsocket
